package com.ilop.sthome.ui.activity.mine;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import androidx.core.content.ContextCompat;

import com.aliyun.iot.aep.sdk.login.LoginBusiness;
import com.aliyun.iot.aep.sdk.login.data.UserInfo;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.ilop.sthome.ui.activity.main.ContainLoginActivity;
import com.example.common.base.OnCallBackToRefresh;
import com.example.common.utils.LiveDataBus;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.mvp.contract.mine.PersonalContract;
import com.ilop.sthome.mvp.present.mine.PersonalPresenter;
import com.ilop.sthome.ui.dialog.BaseDialog;
import com.siterwell.familywellplus.R;
import com.siterwell.familywellplus.databinding.ActivityPersonalBinding;

/**
 * @author skygge
 * @date 2020-01-07.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：个人中心页面
 */
public class PersonalActivity extends ContainLoginActivity<PersonalPresenter, ActivityPersonalBinding> implements PersonalContract.IView {

    private String mNickName = "";
    private String mImageUrl;
    private boolean isPhone;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal;
    }

    @Override
    protected void initialize() {
        super.initialize();
        UserInfo userInfo = LoginBusiness.getUserInfo();
        if (userInfo != null) {
            if (!TextUtils.isEmpty(userInfo.userPhone)) {
                isPhone = true;
            } else if (!TextUtils.isEmpty(userInfo.userEmail)) {
                isPhone = false;
            }
        }
    }

    @Override
    protected void initPresent() {
        super.initPresent();
        mPresent = new PersonalPresenter(mContext);
    }

    @Override
    protected void initView() {
        super.initView();
        mDBind.tvSavePersonal.setTextColor(ContextCompat.getColor(mContext, R.color.text_normal));
        mDBind.tvSavePersonal.setEnabled(false);
        if (isPhone){
            mDBind.userEmailTitle.setVisibility(View.GONE);
        }else {
            mDBind.userPhoneTitle.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {
        super.initData();
        mPresent.getUserInfo();
        LiveDataBus.get().with(CommonId.UPLOAD_IMAGE_SUCCESS, String.class).observe(this, this::showUserImg);
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.ivPersonalBack.setOnClickListener(view -> whetherToSave());
        mDBind.tvSavePersonal.setOnClickListener(v -> savePersonal());
        mDBind.ivUserImg.setOnClickListener(v -> {
            Intent intent  = new Intent(mContext, HeadPortraitActivity.class);
            intent.putExtra(CommonId.KEY_MODIFY, true);
            startActivity(intent);
        });
        mDBind.userNickname.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().equals(mNickName)){
                    mDBind.tvSavePersonal.setTextColor(ContextCompat.getColor(mContext, R.color.text_normal));
                    mDBind.tvSavePersonal.setEnabled(false);
                }else {
                    mDBind.tvSavePersonal.setTextColor(ContextCompat.getColor(mContext, R.color.main_color));
                    mDBind.tvSavePersonal.setEnabled(true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void whetherToSave(){
        String nickname = mDBind.userNickname.getText().toString();
        if (mNickName!=null && !mNickName.equals(nickname)){
            BaseDialog mDialog = new BaseDialog(mContext, new OnCallBackToRefresh() {
                @Override
                public void onConfirm() {
                    savePersonal();
                }

                @Override
                public void onCancel() {
                    finish();
                }
            });
            mDialog.setMsg(mContext.getString(R.string.save_or_not));
            mDialog.show();
        }else {
            finish();
        }
    }

    private void savePersonal(){
        hideSoftKeyboard();
        String nickname = mDBind.userNickname.getText().toString();
        String phone = mDBind.userPhone.getText().toString();
        String email = mDBind.userMail.getText().toString();
        mPresent.onSaveUserInfo(nickname, phone, email, mImageUrl);
        showProgressDialog();
    }

    @Override
    public void showNickName(String nickname) {
        mNickName = nickname;
        if (nickname == null || nickname.contains("[{")){
            mDBind.userNickname.setText(null);
        }else {
            mDBind.userNickname.setText(nickname);
        }
    }

    @Override
    public void showPhone(String phone) {
        mDBind.userPhone.setText(phone);
    }

    @Override
    public void showEmail(String email) {
        mDBind.userMail.setText(email);
    }

    @Override
    public void showUserImg(String path) {
        if (!TextUtils.isEmpty(path)){
            mImageUrl = path;
            Glide.with(mContext)
                    .load(path)
                    .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
                    .apply(RequestOptions.skipMemoryCacheOf(true))
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .into(mDBind.userImg);
        }else {
            mImageUrl = "";
            Glide.with(mContext)
                    .load(R.mipmap.head_default)
                    .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
                    .apply(RequestOptions.skipMemoryCacheOf(true))
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .into(mDBind.userImg);
        }
    }

    @Override
    public void showToastMsg(String msg) {
        dismissProgressDialog();
        showToast(msg);
    }

    @Override
    public void finishActivity() {
        dismissProgressDialog();
        setResult(1);
        finish();
    }

    @Override
    public void onBackPressed() {
        whetherToSave();
    }
}
